import React, {PureComponent} from "react";
import {
    View,
    Button,
    Text,
    StyleSheet,
    TextInput,
    Switch,
    ScrollView,
    Dimensions,
    TouchableOpacity,
    ToastAndroid,
    Linking,
    Platform,
    SafeAreaView,
    DeviceEventEmitter,
    Image,
} from "react-native";
import color from "../../../widget/color";
import ItemCell from "../../../widget/ItemCell";
const {width} = Dimensions.get('window')
import MineEditPasswordDialog from "../../../widget/dialog/MineEditPasswordDialog";

import * as CacheManager from 'react-native-http-cache'
import DeviceInfo from 'react-native-device-info'
import DeviceStorage from '../../../utils/DeviceStorage'
import define from '../../../utils/define'
import Tips from 'react-native-root-tips'
type Props = {
    navigation:any,
}
export default class MineSettingScene extends PureComponent<Props> {

    state = {
        course_value: false,//课程提醒滑动按钮默认关闭
        wifi_value: false,//wifi滑动按钮默认关闭
        cacheSize: ""
    }

    static navigationOptions = ({navigation}: any) => ({
        headerTintColor: 'black',
        title: '设置',
        headerStyle: {backgroundColor: 'white'},
        headerRight: <Text/>,
        headerLeft:<TouchableOpacity onPress={()=>{
            navigation.goBack()
        }}>
            <Image style={{marginLeft:12}} source={require('../../../../res/img/gobal_back.png')}/>
        </TouchableOpacity>
    })

    constructor(props) {
        super(props)
        this.state = {
            version_code: DeviceInfo.getVersion(),
            isLogin:false,
            showPwd: false,
        };
    }


    render() {
        return (
            <SafeAreaView style={{flex:1,backgroundColor:'white'}}>
                <ScrollView>
                    <TouchableOpacity onPress={()=>this.clearCache()}>
                        <ItemCell title='清理缓存' subtitle={this.state.cacheSize} arrow={true}/>
                    </TouchableOpacity>
                    <View style={{height:0.5,marginLeft:12,width:width - 24 ,backgroundColor:'#DFDFDF'}}/>
                    <TouchableOpacity onPress={()=>this.checkForUpdate()}>
                        <ItemCell title='检测更新' subtitle={'当前版本'+this.state.version_code} arrow={true}/>
                    </TouchableOpacity>
                    <View style={{height:0.5,marginLeft:12,width:width - 24 ,backgroundColor:'#DFDFDF'}}/>
                    <TouchableOpacity onPress={()=>this.callPhone()}>
                        <ItemCell title='客服电话' subtitle='客服电话' arrow={true}/>
                    </TouchableOpacity>
                    <View style={{height:0.5,marginLeft:12,width:width - 24 ,backgroundColor:'#DFDFDF'}}/>
                    <TouchableOpacity onPress={this.wechatShareImageTimeline}>
                        <ItemCell title='账号' subtitle='hyw77875678' arrow={false}/>
                    </TouchableOpacity>
                    <View style={{height: 0.5, marginLeft: 12, width: width - 24, backgroundColor: '#DFDFDF'}}/>
                    <TouchableOpacity onPress={() => this.setState({showPwd: true})}>
                        <ItemCell title='修改密码' arrow={true}/>
                    </TouchableOpacity>
                    <View style={{height:0.5,marginLeft:12,width:width - 24 ,backgroundColor:'#DFDFDF'}}/>
                </ScrollView>
                <MineEditPasswordDialog show={this.state.showPwd} closeModal={(show) => {
                    this.setState({showPwd: show})
                }}  {...this.props}/>
                {this.loginOut()}
            </SafeAreaView>
        )
    }

    loginOut(){
        if (this.state.isLogin){
            return <TouchableOpacity
                style={{backgroundColor:'#E4E4E4',justifyContent:'center',alignItems:'center',height:50}} onPress={()=>{
                DeviceStorage.delete(define.token)
                DeviceStorage.delete(define.profile)
                const {goBack,state} = this.props.navigation;
                state.params.callback('回调参数');
                goBack()
                DeviceEventEmitter.emit('loginOut');

            }}>
                <Text style={{fontWeight:'bold',fontSize:16,color:'white'}}>退出登录</Text>
            </TouchableOpacity>
        } else {
            return <View/>
        }
    }
    /**
     * 清理缓存
     */
    clearCache() {
        CacheManager.clearCache();
        // 这里貌似清除不能全部清除为0，这里直接写死0即可。
        this.setState({cacheSize: '0M'});
        Tips.showWarn('清除缓存成功！', {mask: true})
    }

    /**
     * 客服电话
     */
    callPhone() {
        return Linking.openURL('tel:62156118')
    }

    //利用code-push进行版本更新检测
    checkForUpdate() {
        // if (Platform.OS === 'ios') {
        //     codePush.sync({
        //         updateDialog: {
        //             appendReleaseDescription: true,
        //             descriptionPrefix: '\n\n更新内容：\n',
        //             title: '发现新版本',
        //             mandatoryUpdateMessage: '',
        //             mandatoryContinueButtonLabel: '更新',
        //         },
        //         installMode: codePush.InstallMode.IMMEDIATE,
        //         // deploymentKey: CODE_PUSH_PRODUCTION_KEY,
        //     });
        //
        // } else if (Platform.OS === 'android') {
        //     codePush.sync({
        //         updateDialog: {
        //             appendReleaseDescription: true,
        //             descriptionPrefix: '\n\n更新内容：\n',
        //             title: '发现新版本',
        //             mandatoryUpdateMessage: '',
        //             mandatoryContinueButtonLabel: '更新',
        //         },
        //         mandatoryInstallMode: codePush.InstallMode.IMMEDIATE,
        //         // deploymentKey: CODE_PUSH_PRODUCTION_KEY,
        //     });
        // }
    }

    /**
     * 计算缓存大小
     */
    componentDidMount() {
        this.getCacheSize()
        DeviceStorage.get(define.token)
            .then(res=>{
                if (res){
                    this.setState({isLogin:true})
                } else {
                    this.setState({isLogin:false})

                }
            })
            .catch(err=>{
                this.setState({isLogin:false})

            })
    }

    // 获得缓存大小
    async getCacheSize() {
        const data = await CacheManager.getCacheSize();
        const size = data / (1024 * 1024);
        this.setState({cacheSize: size.toFixed(2) + 'M'});
    }

    // getCacheSize() {
    //     const data = await CacheManager.getCacheSize();
    //     const size = data / (1024 * 1024);
    //     this.setState({ cacheSize: size.toFixed(2) + 'M'});
    // }

    _onChangeText(text) {
        this.setState({change: (100 - text.length)})
    }
}